package com.qy.mybatisplus.web;


import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qy.mybatisplus.entity.Role;
import com.qy.mybatisplus.entity.User;
import com.qy.mybatisplus.mapper.UserMapper;
import com.qy.mybatisplus.service.MPRoleService;
import com.qy.mybatisplus.service.MPUserService;
import com.qy.mybatisplus.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author qy
 * @since 2019-12-10
 */
@RestController
@RequestMapping("user")
public class UserAction {

    @Autowired
    private MPUserService userService;

    @Autowired
    private MPRoleService roleService;

    @RequestMapping(value = "show", method = RequestMethod.GET)
    public Result show() {
        Page<User> users = userService.selectPage(new Page<>(1, 10));
        return Result.ok("成功", users);
    }

    //乐观锁--主要是@Version
    @RequestMapping(value = "update", method = RequestMethod.PUT)
    public Result update(@RequestBody User user) {
        //获取对象
        User user1 = userService.selectById(2);
        //需要修改的字段
        User u = new User();
        u.setId(user1.getId());
        u.setVersion(user.getVersion());
        u.setUserName("aaa");
        u.setPassWord(user1.getPassWord());
        //修改
        return Result.ok("成功", userService.updateById(u));
    }

    //悲观锁 --select * from ... for update
    @RequestMapping(value = "updatePessimistic", method = RequestMethod.PUT)
    public Result updatePessimistic(@RequestBody User user) {
        return Result.ok("成功", userService.increaseNoSafe(user));
    }

    @Autowired
    private UserMapper userMapper;

    //insert
    @RequestMapping(value = "insert", method = RequestMethod.GET)
    public Result insert() {
        User user1 = new User();
        user1.setUserName("aaassd");
        return Result.ok("成功", userMapper.insert(user1));
    }

    @RequestMapping(value = "updateR", method = RequestMethod.GET)
    public Result updateR() {

        Role role = roleService.selectById(2);
        //需要修改的字段

        Role role1 = new Role();
        role1.setId(role.getId());
        role1.setVersion(role.getVersion());
        role1.setName("ssssssss");
        return Result.ok("成功", roleService.updateById(role1));
    }

    @RequestMapping(value = "selectR", method = RequestMethod.GET)
    public Result selectR() {

        return Result.ok("成功", roleService.selectById(2));
    }



}
